package org.rocket.spring.security.browser.web;

import org.apache.commons.lang3.StringUtils;
import org.rocket.spring.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author He Peng
 * @create 2018-01-22 2:28
 * @update 2018-01-22 2:28
 * @updatedesc : 更新说明
 * @see
 */

@RestController
public class BrowserSecurityController {

    private static final Logger LOG = LoggerFactory.getLogger(BrowserSecurityController.class);

    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @RequestMapping(path = "/auth/require")
    public ResponseEntity<Map<String , Object>> requireAuthentication(HttpServletRequest request , HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if (Objects.nonNull(savedRequest)) {
            String redirectUrl = savedRequest.getRedirectUrl();
            LOG.info("引发跳转的 url ==》 {} " , redirectUrl);
            if (StringUtils.endsWith(redirectUrl , ".html")) {
                this.redirectStrategy.sendRedirect(request , response , this.securityProperties.getBrowser().getLoginPage());
            }
        }
        Map<String , Object> resObj = new HashMap();
        resObj.put("message" , "需要进行身份认证");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(resObj);
    }
}
